import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Card, Col, Empty, Form, message, Modal, Row, Tabs, Tag} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm, ProFormDateTimeRangePicker,
  ProFormDigit, ProFormSelect,
  ProFormText, ProFormTextArea,
} from '@ant-design/pro-form';
import {isEmpty, isSuccess} from "@/utils/utils";
import {Marketing} from "@/services/api-functions";
import {SYS_ENUMS} from "@/utils/constants";
import type {PositionModRequest, StrategyModRequest} from "@/services/api-types";

const handlePositionEdit = async (fields: any, select: any) => {
  try {
    const rpo: PositionModRequest = {
      id: select?.id ?? '',
      code: fields.code,
      name: fields.name,
      positionType: fields.positionType,
      remark: fields.remark,
      sizeLimit: fields.sizeLimit,
      positionInfo: fields.limitSecond ? {limitSecond: fields.limitSecond} : {}
    }
    if (isSuccess((select && select.id ? (await Marketing.positionEdit(rpo)) : (await Marketing.positionAdd(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const handleStrategyEdit = async (fields: any, select: any, position: any) => {
  try {
    const startTime = fields.timeRange && fields.timeRange.length > 1 ? fields.timeRange[0] : null
    const endTime = fields.timeRange && fields.timeRange.length > 1 ? fields.timeRange[1] : null
    if(isEmpty(startTime) || isEmpty(endTime)){
      message.error('请设置开始时间和结束时间')
      return false
    }
    const rpo: StrategyModRequest = {
      id: select?.id ?? '',
      contentId: fields.contentId,
      state: fields.state,
      positionId: position.id,
      startTime,
      endTime,
    }
    if (isSuccess((select && select.id ? (await Marketing.strategyEdit(rpo)) : (await Marketing.strategyAdd(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const handlePublishStatus = async (select: any, state: string) => {
  if (!select) return true;
  try {
    if (isSuccess((await Marketing.strategyOperate(state, select.id))?.code)) {
      message.success('UP' === state ? '上架成功' : '下架成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};


const PutOnList: React.FC<any> = () => {

  const [formRef] = Form.useForm()
  const [strategyFormRef] = Form.useForm()
  const [visible, handleVisible] = useState<boolean>(false);
  const [strategyVisible, handleStrategyVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const strategyUPActionRef = useRef<ActionType>();
  const strategyDOWNActionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>(undefined);
  const [currentStrategy, setCurrentStrategy] = useState<any>(undefined);
  const [active, setActive] = useState<any>(undefined);
  const initPositionFiledValue = (id: any = undefined, callBack: Function) => {
    if (id) {
      Marketing.positionDetail(id).then(({code, data}) => {
        if (isSuccess(code)) {

          formRef?.setFieldsValue({
            code: data.code,
            name: data.name,
            positionType: data.positionType,
            remark: data.remark,
            sizeLimit: data.sizeLimit,
            limitSecond: data?.positionInfo?.limitSecond
          })
          if (callBack) {
            callBack()
          }
        }
      })
    }
  }

  const initStrategyFiledValue = (strategy: any = undefined, callBack: Function) => {
    if (strategy) {
      strategyFormRef?.setFieldsValue({
        contentId: strategy.contentId,
        state: strategy.state,
        timeRange: [strategy.startTime??undefined, strategy.endTime??undefined]
      })
      if (callBack) {
        callBack()
      }
    }
  }

  const queryStrategyList = async (position: any, type: 'UP' | 'DOWN') => {
    const {data, code}: any = await Marketing.strategyList(position?.id, type);

    return {data, success: isSuccess(code), total: isSuccess(code) ? data?.length : 0};
  }

  const selectPosition = async (position: any) => {
    setActive(position)
    if (strategyUPActionRef.current) {
      strategyUPActionRef.current?.reload()
    }

    if (strategyDOWNActionRef.current) {
      strategyDOWNActionRef.current?.reload()
    }
  }

  const columns: ProColumns[] = [
    {
      title: '关键词',
      dataIndex: 'keyword',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '内容名称',
      dataIndex: 'contentName',
      width: 200,
      ellipsis: true,
      render: (dom, record) => {
        return (
          <a
            onClick={() => {
              setCurrentStrategy(record);
              initStrategyFiledValue(record, () => handleStrategyVisible(true))
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '生效状态',
      dataIndex: 'effective',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '投放点',
      dataIndex: 'positionCode',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '上架状态',
      dataIndex: 'state',
      valueEnum: {
        UP: {text: '已上架', status: 'Success'},
        DOWN: {text: '已下架', status: 'Error'},
      },
      width: 100,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      width: 170,
      hideInForm: true,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      width: 170,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      width: 200,
      render: (_, record) => [
        <a key="edit"
           onClick={() => {
             setCurrentStrategy(record);
             initStrategyFiledValue(record, () => handleStrategyVisible(true))
           }}
        >编辑</a>,
        record.state === 'UP'
          ? <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要下架 <Tag color='#108ee9'>{record.contentName}</Tag> 吗？</span>,
            okText: '下架',
            cancelText: '取消',
            onOk: async () => {
              if (await handlePublishStatus(record, 'DOWN')) {
                strategyDOWNActionRef.current?.reload()
                strategyUPActionRef.current?.reload()
              }
            },
          })}>下架</a>
          : <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要上架 <Tag color='#108ee9'>{record.contentName}</Tag> 吗？</span>,
            okText: '上架',
            cancelText: '取消',
            onOk: async () => {
              if (await handlePublishStatus(record, 'UP')) {
                strategyDOWNActionRef.current?.reload()
                strategyUPActionRef.current?.reload()
              }
            },
          })}>上架</a>
      ],
    },
  ];
  const positionColumns: ProColumns[] = [
    {
      title: 'CODE',
      dataIndex: 'code',
      hideInForm: true,
      hideInSearch: true,
      render: (dom, record) => <a onClick={() => selectPosition(record)}>{dom}</a>,
    },
    {
      title: '名称',
      dataIndex: 'name',
      hideInForm: true,
      hideInSearch: true,
      render: (dom, record) => <a onClick={() => selectPosition(record)}>{dom}</a>,
    },
    {
      title: '类别',
      dataIndex: 'positionType',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: SYS_ENUMS.MARKETING_POSITION_TYPE,
      render: (dom, record) => <a onClick={() => selectPosition(record)}>{dom}</a>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      render: (_, record) => [
        <a key="edit"
           onClick={() => {
             setCurrentRow(record)
             initPositionFiledValue(record.id, () => handleVisible(true))
           }}
        >编辑</a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <Row gutter={16}>
        <Col span={8}>
          <ProTable<any, any>
            headerTitle='投放点列表'
            actionRef={actionRef}
            rowKey="id"
            search={false}
            toolBarRender={() => [
              <Button
                type="primary"
                key="primary"
                onClick={() => handleVisible(true)}>
                <PlusOutlined/> 添加投放点
              </Button>,
            ]}
            request={async (params) => {

              const {data, code}: any = await Marketing.positionList(params);

              if (isSuccess(code) && !currentRow && data.length > 0) {
                setActive(data[0])
              }

              return {data, success: isSuccess(code), total: isSuccess(code) ? data?.length : 0};
            }}
            columns={positionColumns}
            rowClassName={record => currentRow && record.id === currentRow.id ? 'table_active' : ''}
          />
        </Col>
        <Col span={16}>
          {
            active
              ? <Card title={<span>投放点 &nbsp;— &nbsp;<Tag color='#108ee9'>{active?.name}</Tag></span>}
                      bordered={false}>
                <Tabs defaultValue='UP'>
                  <Tabs.TabPane tab='已上架' key='UP'>
                    <ProTable<any, any>
                      headerTitle='策略列表'
                      actionRef={strategyUPActionRef}
                      rowKey="key"
                      search={false}
                      toolBarRender={() => [
                        <Button
                          type="primary"
                          key="primary"
                          onClick={() => handleStrategyVisible(true)}>
                          <PlusOutlined/> 添加策略
                        </Button>,
                      ]}
                      request={async () => queryStrategyList(active, 'UP')}
                      columns={columns}
                    />
                  </Tabs.TabPane>
                  <Tabs.TabPane tab='已下架' key='DOWN'>
                    <ProTable<any, any>
                      headerTitle='策略列表'
                      actionRef={strategyDOWNActionRef}
                      rowKey="key"
                      search={false}
                      toolBarRender={() => [
                        <Button
                          type="primary"
                          key="primary"
                          onClick={() => handleStrategyVisible(true)}>
                          <PlusOutlined/> 添加策略
                        </Button>,
                      ]}
                      request={async () => queryStrategyList(active, 'DOWN')}
                      columns={columns}
                    />
                  </Tabs.TabPane>
                </Tabs>
              </Card>
              : <Empty description='请从左侧选择投放点'/>
          }
        </Col>
      </Row>
      <ModalForm
        title={currentRow ? `编辑【${currentRow?.name}】` : `添加投放点`}
        width="750px"
        form={formRef}
        visible={visible}
        onVisibleChange={v => {
          handleVisible(v)
          if (!v) {
            formRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await handlePositionEdit(value as any, currentRow)) {
            handleVisible(false);
            formRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText label='CODE' required rules={[{required: true, message: '请填写CODE',},]} name="code"/>
        <ProFormText label='名称' required rules={[{required: true, message: '请填写名称',},]} name="name"/>
        <ProFormSelect label='分类' required rules={[{required: true, message: '请填选择分类',},]} name='positionType'
                       initialValue={SYS_ENUMS.MARKETING_POSITION_TYPE.APP_CYCLE_IMAGE.value}
                       options={[
                         {
                           label: SYS_ENUMS.MARKETING_POSITION_TYPE.APP_CYCLE_IMAGE.label,
                           value: SYS_ENUMS.MARKETING_POSITION_TYPE.APP_CYCLE_IMAGE.value
                         },
                         {
                           label: SYS_ENUMS.MARKETING_POSITION_TYPE.PC_CYCLE_IMAGE.label,
                           value: SYS_ENUMS.MARKETING_POSITION_TYPE.PC_CYCLE_IMAGE.value
                         },
                         {
                           label: SYS_ENUMS.MARKETING_POSITION_TYPE.APP_RESOURCES.label,
                           value: SYS_ENUMS.MARKETING_POSITION_TYPE.APP_RESOURCES.value
                         },
                       ]}/>
        <ProFormDigit label='间隔时间（秒）' required initialValue={3} rules={[{required: true, message: '请设置间隔时间',},]}
                      name="limitSecond"/>
        <ProFormTextArea label='备注' required rules={[{required: true, message: '请填写备注',},]} name="remark"/>
        <ProFormDigit label='策略上限条数' required initialValue={3} rules={[{required: true, message: '请填写策略上限条数',},]}
                      name="sizeLimit"/>
      </ModalForm>

      <ModalForm
        title={currentStrategy ? `编辑【${active?.name}-${currentStrategy.contentName}】` : `添加【${active?.name}】策略`}
        width="750px"
        form={strategyFormRef}
        visible={active && strategyVisible}
        onVisibleChange={v => {
          handleStrategyVisible(v)
          if (!v) {
            strategyFormRef?.resetFields()
            setActive(undefined)
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await handleStrategyEdit(value as any, currentStrategy, active)) {
            handleStrategyVisible(false);
            strategyFormRef?.resetFields()
            if (strategyUPActionRef.current) {
              strategyUPActionRef.current.reload();
            }
            if (strategyDOWNActionRef.current) {
              strategyDOWNActionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='状态' required rules={[{required: true, message: '请填选择状态',},]} name='state'
                       initialValue='UP' options={[{label: '上架', value: 'UP'}, { label: '下架', value: 'DOWN'},]}/>
        <ProFormDateTimeRangePicker required label='生效时间' name='timeRange'/>
        <ProFormSelect label='内容' name='contentId' required rules={[{required: true, message: '请设置内容',},]}
                       request={async (params) => {
                         const {code, data} = await Marketing.contentList({
                           current: 1,
                           pageSize: 20,
                           name: params.keyWords ?? '',
                         })
                         return isSuccess(code) ? (data.data ?? []).map((item: any) => {
                           const {name, id} = item
                           return {label: `${name}`, value: id}
                         }) : []
                       }} showSearch/>
      </ModalForm>
    </PageContainer>
  );
};

export default PutOnList;
